<?php 


class EntryMedias {
	
	
	private $entryid;
	private $medias;
	
	public function __construct($entryid) {
		$this->entryid = $entryid;
	}
	
	
    public function getMedias(){
    
        preg_match_all("#<embed(.*?)<\/embed>#", $this->entrycode, $embeds);
        preg_match_all("#<img(.*?)>#", $this->entrycode, $images);
    
        if(!empty($embeds[0])){
            foreach($embeds[0] as $embed){
                if(strstr($embed, 'youtube') != false){
                    $media['videos'][] = $embed;
                }else if(strstr($embed, 'goear') != false){
                    $media['sounds'][] = $embed;
                }
            }
        }
        if(!empty($images[0])){
            foreach($images[0] as $image){
                if(strstr($image, 'blogger.com/img/') == false){
                    preg_match("# src=\"(.*?)\"#", $image, $src);
                    preg_match("# style=\"(.*?)\"#", $image, $style);
                    preg_match("# id=\"(.*?)\"#", $image, $id);
                    $cleanimage = str_replace($style[0], '', str_replace($id[0], '', $image));
                    $media['images'][] = '<a href="'.$src[1].'">'.$cleanimage.'</a>';
                }
            }
        }
    
        $this->medias = $media;
    }
    
        
    public function saveMedias() {
        
        if (!empty($this->medias)) {
            
            if (!empty($this->medias['sounds'])) {
                $this->insertMedia($this->entryid, $this->medias['sounds'], 'sounds');
            }
            
            if (!empty($this->medias['videos'])) {
                $this->insertMedia($this->entryid, $this->medias['videos'], 'videos');
            }
            
            if (!empty($this->medias['images'])) {
                $this->insertMedia($this->entryid, $this->medias['images'], 'images');
            }
        }
    }
    
    
	public function insertMedia($entryid, $values, $table){
	
	    global $DB;
	
	    if($values){
	        foreach($values as $value){
	
	            $sql = "INSERT INTO ".$table." (entryid, value) VALUES (?, ?)";
	            $DB->executeSql($sql, array($entryid, $value));
	        }
	    }
	}
    
}

?>